package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
)

const BackupConfigFileName = "./configs/push3d.json"

type Config struct {
	fileName string

	DBUrl       string
	DBName      string
	CompanyName string
	CompanyId   int
	Teams       []struct {
		Name string
		Id   string
	}
	TeamIds []string
	Rids    []string
	Gps     struct {
		Host      string
		Id        string
		Interval  int
		Active    bool
		MaxRecord int
	}
	Tire struct {
		Host                     string
		Id                       string
		Interval                 int
		Active                   bool
		NeedSensorLost           bool
		MaxRecord                int
		FixData                  bool
		MaxTemperature           int
		WarningRepeatTimes       int
		ErrorPressureRange       int
		ErrorPressureRepeatTimes int
	}
	HttpHeaders []struct {
		Key   string
		Value string
	}
	Failed struct {
		SuccessFlag   int
		Action        int
		RetryTimes    int
		RetryInterval int
	}
	Log struct {
		Type int
		Path string
	}
}

func loadConfig(file string) (*Config, error) {
	if file == "" {
		file = os.Args[0] + ".json"
	}
	if _, err := os.Stat(file); os.IsNotExist(err) {
		file = BackupConfigFileName
	}
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	var cfg Config
	err = json.Unmarshal(buf, &cfg)
	if err == nil {
		cfg.fileName = file
	} else {
		return nil, err
	}

	cfg.TeamIds = make([]string, 0)
	for _, v := range cfg.Teams {
		if v.Id != "" {
			cfg.TeamIds = append(cfg.TeamIds, v.Id)
		}
	}

	return &cfg, err
}

func (p *Config) Save() error {
	buf, _ := json.MarshalIndent(p, "", "\t")

	return ioutil.WriteFile(p.fileName, buf, os.ModePerm)
}
